﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DiskCheck
{
    public partial class Form1 : Form
    {
        private BackgroundWorker bgw = new BackgroundWorker();
        public Form1()
        {
            InitializeComponent();
            Icon ic = new Icon("./Logo.ico");
            this.Icon = ic;
            bgw.WorkerReportsProgress = true;
            bgw.WorkerSupportsCancellation = true;
            this.bgw.DoWork += new System.ComponentModel.DoWorkEventHandler(this.bgw_DoWork);
            this.bgw.RunWorkerCompleted += Bgw_RunWorkerCompleted;
            this.bgw.ProgressChanged += Bgw_ProgressChanged;
            SelectQuery selectQuery = new SelectQuery("select * from win32_logicaldisk");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(selectQuery);
            foreach (ManagementObject disk in searcher.Get())
            {
                cmb.Items.Add(disk["Name"].ToString());
            }
            if (cmb.Items.Count == 0)
            {
                MessageBox.Show("未发现磁盘");
            }
            else
            {
                cmb.SelectedIndex = 0;
            }
            string filename = "./DiskName.txt";
            if (File.Exists(filename))
            {
                cmb.Text = File.ReadAllText(filename);
            }
            filename = "./Title.txt";
            if (File.Exists(filename))
            {
                this.Text = File.ReadAllText(filename);
            }
            btnEnd.Enabled = false;
            btnStart_Click(null, null);
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (cmb.Text == "")
            {
                MessageBox.Show("请选择磁盘");
                return;
            }
            if (numUpDown.Value <= 0)
            {
                MessageBox.Show("请输入警戒容量");
                return;
            }
            List<string> send = new List<string>();
            send.Add(cmb.Text);
            send.Add((numUpDown.Value).ToString());
            bgw.RunWorkerAsync(send);
            btnStart.Enabled = false;
            btnEnd.Enabled = true;
            cmb.Enabled = false;
            numUpDown.Enabled = false;
        }

        private void btnEnd_Click(object sender, EventArgs e)
        {
            bgw.CancelAsync();
        }

        private void bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            List<string> ls = e.Argument as List<string>;
            string diskName = ls[0].Substring(0, 1);
            decimal target = Convert.ToDecimal(ls[1]);
            decimal total = Convert.ToDecimal(GetHardDiskTotalSpace(diskName)) / 1024 / 1024 / 1024;
            while (true)
            {
                for (int i = 0; i < 100; i++)
                {
                    Thread.Sleep(10);
                    if (bgw.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }
                }
                long freespace = GetHardDiskFreeSpace(diskName);
                decimal freespace1 = Convert.ToDecimal(freespace) / 1024 / 1024 / 1024 / total * 100;
                bgw.ReportProgress(0, freespace1.ToString("0.##"));
                if (freespace1 < target)
                {
                    try
                    {
                        //Speech.Read("磁盘报警");
                        Speech.Read();
                    }
                    catch (Exception)
                    {
                        bgw.ReportProgress(0, "err");
                        return;
                    }
                }
            }
        }

        private void Bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            string str = e.UserState as string;
            if (str == "err")
            {
                MessageBox.Show("请检查音响是否接通");
                return;
            }
            if (Convert.ToDecimal(str) < numUpDown.Value)
            {
                tbFree.BackColor = Color.Red;
                FlashWin.FlashWindow(this.Handle, true);
            }
            else
            {
                tbFree.BackColor = Color.White;
            }
            tbFree.Text = str;
        }
        private void Bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            btnStart.Enabled = true;
            btnEnd.Enabled = false;
            cmb.Enabled = true;
            numUpDown.Enabled = true;
            tbFree.Text = "";
            tbFree.BackColor = Color.White;
        }
        public static long GetHardDiskFreeSpace(string str_HardDiskName) //磁盘号
        {
            long freeSpace = new long();
            str_HardDiskName = str_HardDiskName + ":\\";
            System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
            foreach (System.IO.DriveInfo drive in drives)
            {
                if (drive.Name == str_HardDiskName)
                {
                    freeSpace = drive.TotalFreeSpace;//剩余容量
                    //freeSpace = drive.TotalSize; //总容量
                }
            }
            return freeSpace;
        }
        public static long GetHardDiskTotalSpace(string str_HardDiskName) //磁盘号
        {
            long freeSpace = new long();
            str_HardDiskName = str_HardDiskName + ":\\";
            System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
            foreach (System.IO.DriveInfo drive in drives)
            {
                if (drive.Name == str_HardDiskName)
                {
                    //freeSpace = drive.TotalFreeSpace;//剩余容量
                    freeSpace = drive.TotalSize; //总容量
                }
            }
            return freeSpace;
        }
        private void btnTest_Click(object sender, EventArgs e)
        {
            try
            {
                //Speech.Read("磁盘测试");
                Speech.Read();
            }
            catch (Exception err)
            {
                MessageBox.Show("请检查音响是否接通,  " + err.Message);
            }
        }

        private void btnAutoStart_Click(object sender, EventArgs e)
        {
            if (AutoStart.SetMeStart(true))
            {
                MessageBox.Show("设置成功");
            }
            else
            {
                MessageBox.Show("设置失败, 请尝试以管理员身份运行, 并退出杀毒软件");
            }
        }

        //private void btnSet_Click(object sender, EventArgs e)
        //{
        //    if (DialogResult.Yes != MessageBox.Show("是否要设置开机自启", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
        //    {
        //        return;
        //    }
        //    if (AutoStart.SetMeStart(true))
        //    {
        //        MessageBox.Show("设置成功");
        //    }
        //    else
        //    {
        //        MessageBox.Show("设置失败, 请尝试以管理员身份运行, 并退出杀毒软件");
        //    }
        //}
    }
}
